package com.mune.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.mune.common.utils.R;
import com.mune.gulimall.ware.feign.MemberFeignService;
import com.mune.gulimall.ware.vo.FareVo;
import com.mune.gulimall.ware.vo.MemberAddressVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mune.common.utils.PageUtils;
import com.mune.common.utils.Query;

import com.mune.gulimall.ware.dao.WareInfoDao;
import com.mune.gulimall.ware.entity.WareInfoEntity;
import com.mune.gulimall.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
  @Autowired
  MemberFeignService memberFeignService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();

    String key = (String) params.get("key");
    if (!StringUtils.isEmpty(key)) {
      wrapper.and(w -> {
        w.eq("id", key)
                .or().like("name", key)
                .or().like("address", key);
      });
    }
    IPage<WareInfoEntity> page = this.page(
            new Query<WareInfoEntity>().getPage(params),
            wrapper
    );

    return new PageUtils(page);
  }

  @Override
  public FareVo getFare(Long addrId) {
    R info = memberFeignService.info(addrId);
    if (info.getCode() == 0) {
      FareVo fareVo = new FareVo();
      MemberAddressVo memberReceiveAddress = info.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
      });
      String phone = memberReceiveAddress.getPhone();
      fareVo.setAddress(memberReceiveAddress);
      fareVo.setFare(new BigDecimal(phone.substring(phone.length() - 1)));

      return fareVo;
    }
    return null;
  }

}